package com.atguigu.tingshu.user.config;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;

/**
 * @Author：yyj
 * @Package：com.atguigu.tingshu.user.config
 * @Project：tingshu_parent240829
 * @name：WeChatLoginConfig
 * @Date：2025/1/13 19:46
 * @Filename：WeChatLoginConfig
 */
@Configuration
@EnableConfigurationProperties(WeChatProperties.class)
public class WeChatLoginConfig {

    @Bean
    //定义一个WxMaService的bean
    public WxMaService wxMaService(WeChatProperties webProperties){
        //实现wxMaService
        WxMaServiceImpl wxMaService = new WxMaServiceImpl();
        //给定义一个WxMaServiceImpl属性赋值
        WxMaDefaultConfigImpl wxMaDefaultConfig = new WxMaDefaultConfigImpl();
        wxMaDefaultConfig.setAppid(webProperties.getAppId());
        wxMaDefaultConfig.setSecret(webProperties.getAppSecret());

        wxMaService.setWxMaConfig(wxMaDefaultConfig);

        //返回
        return wxMaService;
    }

    @Bean
    public RsaSigner rsaSigner(){
        //获取证书
        ClassPathResource classPathResource = new ClassPathResource("tingshu.jks");
        //获取钥匙工厂对象
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(classPathResource, "tingshu".toCharArray());
        //获取钥匙对
        KeyPair keyPair =  keyStoreKeyFactory.getKeyPair("tingshu", "tingshu".toCharArray());
        //获取私钥
        RSAPrivateKey aPrivate = (RSAPrivateKey)keyPair.getPrivate();

        return new RsaSigner(aPrivate);
    }

}
